﻿// Copyright 2018 Fangling Software Co., Ltd. All Rights Reserved.
// Author: miaochengyu@fLcnc.com (Miaocheng Yu/Zhijun Huo)

import QtQuick 1.1
import com.flcnc.tube 1.0

Rectangle {
  id: pos_monitor_
  color: "transparent"

  QtObject {
    id: internal_
    property int line_height: Math.max((100 + space) / row - space, 20)
    property int axes_counts: 2
    property int row: Math.ceil(axes_counts / col)
    property int col: 2
    property int space: 6
    property bool virtual_visible_: false
    property int font_size: 12

    property bool showArc: false

    // Define static global variant
    property int autoThcMode_MapId: 30329
    property string aUTOARCTHC_CUSTOM: "AutoArcTHC";

    // Define custom index
    property int arcTHC_custom_: -1

    // index->ainid-> AINValue-> arc. map_id[0]
    property int aIN_INDEX: -1
    property int target_ARC_INDEX: 0
    property int aIN: 25
    property int targetArc_id: 2680

    property double real_ARC: 0.00
    property double target_ARC: 0.00
    property int mIN_V_VALUE_INDEX: -1
    property int min_V_Value: 0

    property int mAX_V_VALUE_INDEX: -1
    property int max_V_Value: 5
    property int mIN_ARC_VALUE_INDEX: -1
    property int min_ARC_Value: 200

    property int mAX_ARC_VALUE_INDEX: -1
    property int max_ARC_Value: 600

    //property int the_V_Range:5
    //property int the_ARC_Range:400
    property int aRC_RATIO_INDEX: -1;
    property int arc_ratio: 1;

    property int aIN_RANGE: 65535;
    property int aIN_CHANNEL_MAX_VALUE: 5;
  }

  Column {
    width: parent.width
    spacing: internal_.space
    anchors.bottom: parent.bottom
    Row {
      width: parent.width
      height: internal_.line_height
      visible: internal_.showArc
      spacing: 10
      Text {
        text: qsTr("ReArc:")
        font.pixelSize: internal_.line_height / 1.5
        width: parent.width / 5
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignLeft
        anchors.left: parent.left
        anchors.leftMargin:1
      }
      Text {
        id: realTimeArc
        text: "0.01"
        font.pixelSize: internal_.line_height / 1.5
        width: parent.width / 5
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignRight
        //anchors.right: parent.horizontalCenter
        anchors.rightMargin: 1
      }
      Text {
        text: qsTr("SetArc:")
        font.pixelSize: internal_.line_height / 1.5
        width: parent.width / 5
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignLeft
        //anchors.left: parent.horizontalCenter
        anchors.leftMargin: 25
      }
      Text {
        id: setArc
        text: "0.01"
        font.pixelSize: internal_.line_height /1.5
        width: parent.width / 5
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignRight
        anchors.right: parent.right
        anchors.rightMargin: 15
      }
      Monitor {
        id: arc_monitor_
        timeout: 1500
        running: internal_.showArc
        triggeredOnStart: false
        repeat: true
        onUpdate: {
          if(internal_.arcTHC_custom_ == -1) {
            pos_monitor_.initListModel();
          }
          internal_.real_ARC = pos_monitor_.getArcValue().toFixed(2);
          internal_.target_ARC = pos_monitor_.getTargetValueFromTable(internal_.targetArc_id).toFixed(2);

          //logger_.Info("ReArc:"+String(pos_monitor_.getArcValue())+" "+String(internal_.real_ARC))
          realTimeArc.text = internal_.real_ARC;
          setArc.text = internal_.target_ARC;
        }
      }
    }

    Text {
      visible: internal_.virtual_visible_
      font.pointSize: internal_.font_size
      text: "Virtual Axis:"
    }

    Rectangle {
      id: rec_virtual_
      visible: internal_.virtual_visible_
      width: parent.width
      height: 80
      color: pos_monitor_.color
      border.color: "gray"
      border.width: 2
      Grid {
        anchors.fill: parent
        columns: internal_.col
        spacing: internal_.space
        Repeater {
          model: virtual_axes_
          AxisPosition {
            axis_index: index
            height: internal_.line_height
            width: (pos_monitor_.width - internal_.space) / internal_.col
          }
        }
      }
    }

    Rectangle {
      width: parent.width
      height: internal_.line_height
      color: pos_monitor_.color
      border.color: "gray"
      border.width: 0 // internal_.virtual_visible_ ? 2 : 0
      visible: condition_.isJinFeng() && param_.GetValue(36002) > 0
      Grid {
        anchors.fill: parent
        columns: internal_.col
        spacing: internal_.space
        Rectangle {
          id: jf_sensor_axis_
          height: internal_.line_height
          width: (pos_monitor_.width - internal_.space) / internal_.col
          color: "transparent"
          Text {
            id: jf_sensor_axis_prefix_
            width: parent.width / 2.5
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignLeft
            font.pixelSize: parent.height / 1.5
            anchors.left: parent.left
            anchors.top: parent.top
            anchors.bottom: parent.bottom
            text: "S:"
          }
          Text {
            id: jf_sensor_axis_pos_
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignRight
            font.pixelSize: parent.height / 1.5
            anchors.left: jf_sensor_axis_prefix_.right
            anchors.top: parent.top
            anchors.bottom: parent.bottom
            anchors.right: parent.right
            text: "0"
          }
        }
      }
      Monitor {
        running: jf_sensor_axis_.visible
        onUpdate: {
          var AXIS_DPOS_BASE = 280;
          var JF_SENSOR_AXIS_PARAM_ID = 36002;
          var axis_index = param_.GetValue(JF_SENSOR_AXIS_PARAM_ID);
          var pos = (controller_.GetPlcD(AXIS_DPOS_BASE + axis_index * 2) +
            controller_.GetPlcD(AXIS_DPOS_BASE + axis_index * 2 + 1) * 2147483647) / 1000000;
          jf_sensor_axis_pos_.text = pos.toFixed(2);
          var S_POSTION_VALUE = 358;
          controller_.SetPlcD(S_POSTION_VALUE, jf_sensor_axis_pos_.text * 1000);
        }
      }
    }

    Text {
      visible: internal_.virtual_visible_
      font.pointSize: internal_.font_size
      text: "Real Axis:"
    }

    Rectangle {
      width: parent.width
      height: 100
      color: pos_monitor_.color
      border.color: "gray"
      border.width: internal_.virtual_visible_ ? 2 : 0
      Grid {
        anchors.fill: parent
        columns: internal_.col
        spacing: internal_.space
        Repeater {
          model: real_axes_
          AxisPosition {
            axis_index: index
            height: internal_.line_height
            width: (pos_monitor_.width - internal_.space) / internal_.col
          }
        }
      }
    }

    ListModel {
      id: real_axes_
    }

    ListModel {
      id: virtual_axes_
    }

    Controller {
      id: controller_
      onXMLValueChanged: {
        if( internal_.autoThcMode_MapId == map_id) {
          internal_.showArc = getAutoThcMode3();
        }
        //logger_.Info("map_id:")
        if(internal_.showArc != true  || internal_.arcTHC_custom_<0){
          return;
        }
        if (internal_.aIN_INDEX > 0 && map_id== internal_.aIN_INDEX) {
          internal_.aIN = Number(param_.GetDirtyValue(internal_.aIN_INDEX));
        }
        /*if (internal_.target_ARC_INDEX > 0 && map_id == internal_.target_ARC_INDEX) {
          internal_.target_ARC = Number(param_.GetDirtyValue(internal_.target_ARC_INDEX));
        }*/
        if (internal_.mIN_V_VALUE_INDEX > 0 && map_id == internal_.mIN_V_VALUE_INDEX) {
          logger_.Info("min_V_Value:"+String(internal_.min_V_Value))
          internal_.min_V_Value = Number(param_.GetDirtyValue(internal_.mIN_V_VALUE_INDEX));
        }
        if (internal_.mAX_V_VALUE_INDEX > 0 && map_id ==internal_.mAX_V_VALUE_INDEX) {
          logger_.Info("max_V_Value:"+String(internal_.mAX_V_VALUE))
          internal_.max_V_Value = Number(param_.GetDirtyValue(internal_.mAX_V_VALUE_INDEX));
        }
        if (internal_.mIN_ARC_VALUE_INDEX > 0 && map_id ==internal_.mIN_ARC_VALUE_INDEX) {
          logger_.Info("min_ARC_Value:"+String(internal_.min_ARC_Value))
          internal_.min_ARC_Value = Number(param_.GetDirtyValue(internal_.mIN_ARC_VALUE_INDEX));
        }
        if (internal_.mAX_ARC_VALUE_INDEX > 0 && map_id ==internal_.mAX_ARC_VALUE_INDEX) {
          logger_.Info("max_ARC_Value:"+String(internal_.max_ARC_Value))
          internal_.max_ARC_Value = Number(param_.GetDirtyValue(internal_.mAX_ARC_VALUE_INDEX));
        }
        if (internal_.aRC_RATIO_INDEX > 0 && map_id == internal_.aRC_RATIO_INDEX) {
          internal_.arc_ratio = Number(param_.GetDirtyValue(internal_.aRC_RATIO_INDEX));
        }
        // add range
        internal_.aIN_RANGE = getAdResolution();
        internal_.aIN_CHANNEL_MAX_VALUE = getAdMeasureRange();
      }
    }
    Parameter {
      id: param_
    }
    XmlFunction {
      id: xml_
    }
    Logger {
	    id:logger_
    }
    ConditionScript {
      id: condition_
    }
  }

  function initListModel() {
    /*
     *1.map_id
     *2.view_param_
     *3.map_id,view_param_
     *4.internal_
    */
    var map_id = [];
    var custom_index = xml_.getCustomParamIndex(internal_.aUTOARCTHC_CUSTOM);
    internal_.arcTHC_custom_ = custom_index;

    logger_.Info("custom_index : " + String(custom_index));
    if (custom_index < 0) {
      return map_id;
    }
    map_id.push(xml_.getParamIntIndex(custom_index, 0)); // 0 Ain
    map_id.push(xml_.getParamIntIndex(custom_index, 1)); // 1 Target arc
    map_id.push(xml_.getParamIntIndex(custom_index, 2)); // 2 Real axis
    map_id.push(xml_.getParamIntIndex(custom_index, 3)); // 3 Virtual axis
    map_id.push(xml_.getParamIntIndex(custom_index, 4)); // 4 Input min V-value
    map_id.push(xml_.getParamIntIndex(custom_index, 5)); // 5 Input max V-value
    map_id.push(xml_.getParamIntIndex(custom_index, 6)); // 6 Input min arc
    map_id.push(xml_.getParamIntIndex(custom_index, 7)); // 7 Input max arc
    map_id.push(xml_.getParamIntIndex(custom_index, 8)); // 8 TCH mode [1:PID_RUNNING, 2:PID_SELF_TUNING]
    map_id.push(xml_.getParamIntIndex(custom_index, 9)); // 16 ratio
    internal_.aIN_INDEX = map_id[0];
    // internal_.target_ARC_INDEX = map_id[1];
    internal_.mIN_V_VALUE_INDEX = map_id[4];
    internal_.mAX_V_VALUE_INDEX = map_id[5];
    internal_.mIN_ARC_VALUE_INDEX = map_id[6];
    internal_.mAX_ARC_VALUE_INDEX = map_id[7];
    internal_.aRC_RATIO_INDEX = map_id[9];
    logger_.Info()
    updateArcCollectParam();
  }

  /**
   * @hzj get AutoThcMode 3
  */
  function getAutoThcMode3() {
    var TubeTechParam_autoThcMode_MapId = 30329;
    var index = Number(param_.GetDirtyValue(TubeTechParam_autoThcMode_MapId));
    return index == 3;
  }
  /**
   * @brief Get AD resolution
  */
  function getAdResolution() {
    var TUBETECHPARAM_ADRESOLUTION_MAP = 30331;
    var index = Number(param_.GetDirtyValue(TUBETECHPARAM_ADRESOLUTION_MAP));
    var values = param_.GetEnum(TUBETECHPARAM_ADRESOLUTION_MAP);
    var ad_resolution = 65535;
    if (index >= 0 && index < values.length) {
      ad_resolution = Number(values[index]);
    }
    return ad_resolution;
  }

  /*
   * @brief Get AD measure range
  */
  function getAdMeasureRange() {
    var TUBETECHPARAM_ADMEASURERANGEMODE_MAP = 30330;
    var index = Number(param_.GetDirtyValue(TUBETECHPARAM_ADMEASURERANGEMODE_MAP));
    var ad_measure_range = 5;
    if(index==0) {
      ad_measure_range=10;
    }else if(index==4) {
      ad_measure_range=5
    }
    return ad_measure_range;
  }

  function updateArcCollectParam() {
    /*
     *1.aIN_INDEX,mIN_V_VALUE_INDEX,mAX_V_VALUE_INDEX
     *mIN_ARC_VALUE_INDEX,mAX_ARC_VALUE_INDEX,aRC_RATIO_INDEX>0
     *2.param_get,update
    */

    logger_.Info("now at updateArcCollectParam function  ")

    if (internal_.aIN_INDEX > 0) {
      internal_.aIN = Number(param_.GetDirtyValue(internal_.aIN_INDEX));
      logger_.Info("aIN: "+String(internal_.aIN))
    }
    //add target_ARC 
    if (internal_.mIN_V_VALUE_INDEX > 0) {
      internal_.min_V_Value = Number(param_.GetDirtyValue(internal_.mIN_V_VALUE_INDEX));
      logger_.Info("min_V_Value:  "+String(internal_.min_V_Value))
    }
    if (internal_.mAX_V_VALUE_INDEX > 0) {
      internal_.max_V_Value = Number(param_.GetDirtyValue(internal_.mAX_V_VALUE_INDEX));
      logger_.Info("max_V_Value:  "+String(internal_.max_V_Value))
    }
    if (internal_.mIN_ARC_VALUE_INDEX > 0) {
      internal_.min_ARC_Value = Number(param_.GetDirtyValue(internal_.mIN_ARC_VALUE_INDEX));
      logger_.Info("min_ARC_Value:  "+String(internal_.min_ARC_Value))
    }
    if (internal_.mAX_ARC_VALUE_INDEX > 0) {
      internal_.max_ARC_Value = Number(param_.GetDirtyValue(internal_.mAX_ARC_VALUE_INDEX));
      logger_.Info("max_ARC_Value:  "+String(internal_.max_ARC_Value))
    }
    if (internal_.aRC_RATIO_INDEX > 0) {
      internal_.arc_ratio = Number(param_.GetDirtyValue(internal_.aRC_RATIO_INDEX));
    }
    // add range
    internal_.aIN_RANGE = getAdResolution();
    internal_.aIN_CHANNEL_MAX_VALUE = getAdMeasureRange();
    logger_.Info("now Out updateArcCollectParam function  ")
  }

  // ain_value,to Ar
  function getAInValue(ain_id) {
    if (ain_id < 0) {
      return 0;
    }
    var cmd = "?AIN(" + ain_id.toString() + ")";
    var value = controller_.ExcuteZmcCmd(cmd, false);
    return Number(value);
  }

  function getTargetValueFromTable(targetArc_id) {
    if (targetArc_id < 0) {
      return 0;
    }
    var cmd = "?TABLE(" + targetArc_id.toString() + ")";
    var value = controller_.ExcuteZmcCmd(cmd, false);
    return Number(value);
  }

  // computer ,get Arc
  function getArcValue() {
    /*
     *2.v_range arc_range
     *3.0.0
     *4.get a_value
     *5.arc_ratio,return
    */
    if (internal_.aIN < 0) {
      logger_.Info("aIN:  "+String(internal_.aIN))
      return 0.0;
    }
    var v_range = (Number(internal_.max_V_Value) - Number(internal_.min_V_Value)) / Number(internal_.aIN_CHANNEL_MAX_VALUE) * Number(internal_.aIN_RANGE);
    var arc_range = Number(internal_.max_ARC_Value) - Number(internal_.min_ARC_Value);
    //logger_.Info("min_V_Value:  "+String(internal_.min_V_Value))
    //logger_.Info("max_V_Value:  "+String(internal_.max_V_Value))
    //logger_.Info("min_ARC_Value:  "+String(internal_.min_ARC_Value))
    //logger_.Info("max_ARC_Value:  "+String(internal_.max_ARC_Value))
    //logger_.Info("aIN_CHANNEL_MAX_VALUE:  "+String(internal_.aIN_CHANNEL_MAX_VALUE))
    //logger_.Info("aIN_RANGE:  "+String(internal_.aIN_RANGE))
    if (v_range <= 0.0 || arc_range <= 0.0) {
      logger_.Info("function getArcValue, range:  "+String(v_range)+","+String(arc_range))
      logger_.Info("===============================================")
      return 0.0;
    }
    var a_value = pos_monitor_.getAInValue(internal_.aIN);
    var arc_value = 0.0;
    if (internal_.arc_ratio > 0) {
      arc_value = Number(internal_.min_ARC_Value) + Number(a_value) / Number(v_range) * Number(arc_range);
    } else {
      arc_value = Number(internal_.max_ARC_Value) - Number(a_value) / Number(v_range) * Number(arc_range);
    }
    return arc_value;
  }

  Component.onCompleted: {
    // logger_.Info("showArc:1")
    for (var i = 0, len = controller_.GetAxesCounts(); i < len; i++) {
      if (controller_.GetAxisIsVirtual(i)) {
        virtual_axes_.append({index:i})
      } else if (controller_.GetAxisIsReal(i) || !controller_.GetAxisIsBracket(i)) {
        if (controller_.GetAxisIsMainChuck(i) || !controller_.GetAxisIsChuck(i)) {
          real_axes_.append({index:i})
        }
      }
    }
    internal_.showArc = getAutoThcMode3();
    // logger_.Info("showArc:2")
    internal_.axes_counts = real_axes_.count;
    var TCP_MACHINE_ENABLE = 65000;
    internal_.virtual_visible_ = param_.GetValue(TCP_MACHINE_ENABLE) == "true";
    if(internal_.showArc) {
      // logger_.Info("ready use init in onCompleted")
      initListModel();
    }
  }
}